package com.jason.user.controller;


import com.jason.common.base.BaseController;
import com.jason.common.error.BusinessErrorEnum;
import com.jason.common.error.BusinessException;
import com.jason.common.vo.CommonReturnType;
import com.jason.user.servlce.OtpService;
import com.jason.user.servlce.UserService;
import com.jason.user.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  用户管理控制器
 *
 */
@Slf4j
@Controller
//@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private OtpService otpService;

    private Map<String,String> cacheMap = new ConcurrentHashMap<>();

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @ResponseBody
    @GetMapping("/{id}")
    public UserModel getUserById(@PathVariable(name = "id") Integer id) throws BusinessException {
        UserModel userById = userService.getUserById(id);
        if (userById == null){
            throw new BusinessException(BusinessErrorEnum.USER_NOT_EXIST);
        }
        return userById;
    }

    /**
     * 获取动态口令
     */
    @ResponseBody
    @GetMapping("/otp")
    public CommonReturnType getOTP(String telephone, HttpSession session) throws BusinessException {

        if (StringUtils.isEmpty(telephone)){
            throw new BusinessException(BusinessErrorEnum.PARAM_ILLEGAL_ERROR);
        }
        String otp = otpService.getOTP();
        cacheMap.put(telephone, otp);
//        session.setAttribute(telephone, otp);
        log.info("{}的动态验证码为：{}", telephone, otp);
        return CommonReturnType.success();

    }
    @PostMapping("/otp")
    @ResponseBody
    public CommonReturnType getOTP(String telephone, String otpCode, HttpSession session) throws BusinessException {

        if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(otpCode)){
            throw new BusinessException(BusinessErrorEnum.PARAM_ILLEGAL_ERROR);
        }
        String sessionOtp = cacheMap.get(telephone);
        //String sessionOtp = (String) session.getAttribute(telephone);
        if (!otpCode.equals(sessionOtp)){
            throw new BusinessException(BusinessErrorEnum.CODE_NOT_VALID);
        }
        return CommonReturnType.success();
    }

    /**
     * 注册
     */
    @ResponseBody
    @PostMapping("/registry")
    public CommonReturnType registerByTelephone(@Valid UserModel userModel, HttpSession session) throws BusinessException {

        /**
         * 初始化一些注册时未填写的属性
         */
        userModel.setRegisterType("byPhone");
        userModel.setRegisterAccount(userModel.getTelephone());

        int i = userService.insertUser(userModel);
        if (i == 1){
            //注册成功将user信息放入Session
            session.setAttribute("username", userModel.getName());
            return CommonReturnType.success();
        }
        return CommonReturnType.builder("fail", "注册失败");
    }

    @ResponseBody
    @PostMapping("/launcher")
    public CommonReturnType login(String telephone, String password, HttpSession session) throws BusinessException {
        if (!StringUtils.isEmpty(telephone)){
            Boolean success = userService.authenticate(telephone, password);
            if (success){
                return CommonReturnType.success();
            }
        }
        return CommonReturnType.builder("faild", "登录失败，用户名和密码不正确");
    }
}
